package com.example.himalaya2;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya2.adapters.PlayTrackPageAdapter;
import com.example.himalaya2.base.BaseActivity;
import com.example.himalaya2.interfaces.IPlayerCallback;
import com.example.himalaya2.presenters.PlayerPresenter;
import com.example.himalaya2.utils.LogUtil;
import com.example.himalaya2.views.SobPopWindow;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.XmPlayerManager;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PlayerActivity extends BaseActivity implements IPlayerCallback,ViewPager.OnPageChangeListener{
    private static final String TAG = "PlayerActivity";
    private ImageView mControlBtn;
    private PlayerPresenter mPlayerPresenter;
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");
    private TextView mTotalDuration;
    private TextView mCurrentPosition;
    private SeekBar mDurationBar;
    private int mCurrentProgress = 0;
    private boolean mIsUserTouch = false;
    private ImageView mPlayNextBtn;
    private ImageView mPlayPreBtn;
    private TextView mTitleTv;
    private String mTrackTitle;
    private ViewPager mTrackPageView;
    private PlayTrackPageAdapter mTrackPageAdapter;
    private boolean mIsUserSlidPager = false;
    private ImageView mPlayModeSwitch;
    private XmPlayListControl.PlayMode mCurrentMode = XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP;
    private static Map<XmPlayListControl.PlayMode,XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    static {
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_LIST, XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP);
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP, XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM);
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM, XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP, XmPlayListControl.PlayMode.PLAY_MODEL_LIST);

    }

    private View mPlayListBtn;
    private SobPopWindow mSobPopWindow;
    private ValueAnimator mEnterBgAnimator;
    private ValueAnimator mOutBgAnimator;
    public static final int BG_ANIMATION_DURATION=400;
    private boolean mTextOrder = false;


    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        // TODO 测试播放
        initView();
        mPlayerPresenter = PlayerPresenter.getInstance();
        mPlayerPresenter.registerViewCallback(this);

        // 在进面初始化后，获取数据
        mPlayerPresenter.getPlayList();
        initEven();
        iniBgAnimation();

    }

    private void iniBgAnimation() {
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f,0.6f);
        mEnterBgAnimator.setDuration(BG_ANIMATION_DURATION);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float)valueAnimator.getAnimatedValue();
                updateBgAlpha(value);
            }
        });
        // 退出的
        mOutBgAnimator = ValueAnimator.ofFloat(0.6f,1.0f);
        mOutBgAnimator.setDuration(BG_ANIMATION_DURATION);
        mOutBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float value = (float)valueAnimator.getAnimatedValue();
                updateBgAlpha(value);
            }
        });

    }

    /*
     * 找到各个控件
     * */
    private void initView() {
        mControlBtn = this.findViewById(R.id.play_or_pause_btn);
        mTotalDuration = this.findViewById(R.id.track_duration);
        mCurrentPosition = this.findViewById(R.id.current_position);
        mDurationBar = this.findViewById(R.id.track_seek_bar);
        mPlayNextBtn = this.findViewById(R.id.play_next);
        mPlayPreBtn = this.findViewById(R.id.play_pre);
        mTitleTv = this.findViewById(R.id.track_title);
        if (!TextUtils.isEmpty(mTrackTitle)) {
            mTitleTv.setText(mTrackTitle);
        }
        mTrackPageView = this.findViewById(R.id.track_pager_view);
        // create adapter
        mTrackPageAdapter = new PlayTrackPageAdapter();
        // set adapter
        mTrackPageView.setAdapter(mTrackPageAdapter);
        // 切换播放器模式的按钮
        mPlayModeSwitch = this.findViewById(R.id.player_mode_switch_btn);
        // 播放列表
        mPlayListBtn = this.findViewById(R.id.player_list);
        mSobPopWindow = new SobPopWindow();
    }

    /*
     * 给控件设置相关的事件
     * */
    private void initEven() {
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 如果现在的状态是正在播放就会暂停
                if (mPlayerPresenter.isPlay()) {
                    mPlayerPresenter.pause();
                } else {
                    mPlayerPresenter.play();
                }
                // 如果现在状态是非播放 就会继续播放
            }
        });

        mDurationBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean isFromUer) {
                if (isFromUer) {
                    mCurrentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouch = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 手离开拖动进度条的时候更新进度
                mPlayerPresenter.seekTo((int) mCurrentProgress);
                mIsUserTouch = false;
            }
        });

        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playNext();
                }
            }
        });

        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playPre();
                }
            }
        });

        mTrackPageView.addOnPageChangeListener(this);
        mTrackPageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
               int action = motionEvent.getAction();
               switch (action) {
                   case MotionEvent.ACTION_DOWN:
                       mIsUserSlidPager = true;
                       break;
                   case MotionEvent.ACTION_UP:

               }
               return false;
            }
        });
        mPlayModeSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchPlayMode();
            }
        });
        mPlayListBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //列表按钮 展示播放的列表
                mSobPopWindow.showAtLocation(view, Gravity.BOTTOM,0,0);
                mSobPopWindow.setAnimationStyle(R.style.pop_animation);
                // 处理播放页面的背景给透明度

                // 修改背景有哦一个渐变的过程
                mEnterBgAnimator.start();
            }
        });

        mSobPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mOutBgAnimator.start();
            }
        });
        mSobPopWindow.setPlayListItemClickedListener(new SobPopWindow.PlayListItemClickedListener() {
            @Override
            public void onItemClicked(int position) {
                // 说明播放列表item被点击
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playByIndex(position);
                }
            }
        });
        
        mSobPopWindow.setPlayListPlayModeClickListener(new SobPopWindow.PlayListPlayModeClickListener() {
            @Override
            public void onPlayModeClick() {
                // 切换模式
                switchPlayMode();
            }

            @Override
            public void onOrderClick() {
                // 点击了切换播放顺序和逆序
                // todo
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.reversPlayList();
                }
                mSobPopWindow.updateOrderIcon(!mTextOrder);
                mTextOrder = !mTextOrder;
            }
        });
    }

    private void switchPlayMode() {
        // 处理播放模式改变
        // 默认顺序列表播放
        // 根据当前的模式获取到下一个模式
        XmPlayListControl.PlayMode playMode = sPlayModeRule.get(mCurrentMode);
        if (mPlayerPresenter != null) {
            mPlayerPresenter.switchPlayModel(playMode);
            mCurrentMode = playMode;
            // 由于没有播放模式改变的回调 ，只能在这里修改UI了

        }
    }

    public void updateBgAlpha(float alpha){ // 修改背景的透明度
        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }

    /*
    *
    * 根据当前的状态更新 播放模式图片
    * */
    private void upDatePlayModeBtnImage() {
        int resId = R.drawable.selector_play_mode_list_order;
        switch (mCurrentMode) {
            case PLAY_MODEL_LIST:
                resId = R.drawable.selector_play_mode_list_order;
                break;
            case PLAY_MODEL_RANDOM:
                resId = R.drawable.selector_paly_mode_random;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resId = R.drawable.selector_paly_mode_single_loop;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resId = R.drawable.selector_paly_mode_list_order_looper;
                break;
            default:
                resId = R.drawable.selector_play_mode_list_order;
        }
        mPlayModeSwitch.setImageResource(resId);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallback(this);
            mPlayerPresenter = null;
        }
    }

    @Override
    public void onPLayStart() {
        // 开始播放 修改ui层的暂停按钮
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.stop_normal);
        }
    }

    @Override
    public void onPlayPause() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.play_normal);
        }
    }

    @Override
    public void onPlayStop() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.play_normal);
        }
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> tracks) {
        // 把数据设置到适配器里
        if (mTrackPageAdapter != null) {
            mTrackPageAdapter.setData(tracks);
        }
        if (mSobPopWindow!= null) {
            //数据回来以后，也要给弹出的播放列表来一份
            mSobPopWindow.setListData(tracks);
        }

    }

    @Override
    public void onPlayModelChange(XmPlayListControl.PlayMode model) {
        // 更新播放模式 并且修改ui
        mCurrentMode = model;
        // 更新pop里的播放模式
        mSobPopWindow.upDatePlayMode(mCurrentMode);
        upDatePlayModeBtnImage();

    }

    @Override
    public void onProgressChange(long current, long title) {
        mDurationBar.setMax((int) title);
        // 更新播放的进度，更新进度条
        String totalDuration;
        String currentPosition;
        if (title > 1000 * 60 * 60) {
            totalDuration = mHourFormat.format(title);
        } else {
            totalDuration = mMinFormat.format(title);
        }
        if (mTotalDuration != null) {
        }
        if (title > 1000 * 60 * 60) {
            currentPosition = mHourFormat.format(current);
        } else {
            currentPosition = mMinFormat.format(current);
        }
        if (mTotalDuration != null) {
            mTotalDuration.setText(totalDuration);
        }
        mTotalDuration.setText(totalDuration);
        // 更新当前时间
        mCurrentPosition.setText(currentPosition);
        // 更新进度  计算当前的进度
        if (!mIsUserTouch) {
            mDurationBar.setProgress((int) current);
        }
    }

    @Override
    public void onADLoading() {

    }

    @Override
    public void onAdFinish() {

    }

    @Override
    public void onTrackUpdate(Track track,int position) {
        if (track == null) {
            LogUtil.d(TAG,"onTrackUpdate");
            return;
        }
        mTrackTitle = track.getTrackTitle();
        if (mTitleTv != null) {
            mTitleTv.setText(track.getTrackTitle());
        }
        // update current viewpage when track has changed todo
        // 节目改变后，修改cover
        if (mTrackPageView != null) {
            mTrackPageView.setCurrentItem(position,true);
        }
        // 设置播放列表里当前的位置
        if (mSobPopWindow != null) {
            mSobPopWindow.setCurrentPlayPosition(position);
        }

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

        //当页面选中的时候，就去切换播放的内容
        if (mPlayerPresenter != null&& mIsUserSlidPager == true) {
            mPlayerPresenter.playByIndex(position);
        }
       LogUtil.d(TAG,"onPageSelected");
        mIsUserSlidPager = false;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
